package com.maple.controller.user;


import com.alipay.api.domain.UserVo;
import com.maple.constant.JwtClaimsConstant;
import com.maple.dto.UserLoginDTO;
import com.maple.entity.User;
import com.maple.properties.JwtProperties;
import com.maple.result.Result;
import com.maple.service.UserService;
import com.maple.utils.JwtUtil;
import com.maple.utils.ThreadLocalUtils;
import com.maple.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user/user")
public class UserController {


    @Autowired
    UserService userService;
    @Autowired
    JwtProperties jwtProperties;

    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("用户登录：{}", userLoginDTO);

        User user = userService.login(userLoginDTO);
        Long id = ThreadLocalUtils.getCurrentId();

        Map<String, Object> claim = new HashMap<>();
        claim.put(JwtClaimsConstant.USER_ID, id);

        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claim);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .token(jwt)
                .openid(user.getOpenid())
                .build();
        return Result.success(userLoginVO);

    }




}
